2.3 创建你的第一个 Skill
🎯 本章目标
通过实战创建三个实用 Skill,从简单到复杂,让你完全掌握 Skill 开发流程。
实战 1:Hello Skill(5 分钟入门)
场景
创建一个简单的问候 Skill,当用户说"你好"时,按公司规范回复。
Step 1:创建文件夹
# Personal Skills 位置
mkdir -p ~/.claude/skills/hello-skill
cd ~/.claude/skills/hello-skillStep 2:创建 SKILL.md
---
name: hello-skill
description: Professional greeting skill. Use when user says hello or asks for a greeting.
---
# Hello Skill
## Purpose
Provide professional greetings following company etiquette.
## Usage
When user greets:
1. Respond with: "Hello! Welcome to Acme Corp. How may I assist you today?"
2. Use friendly but professional tone
3. Always end with offer to help
## Examples
- User: "Hi"
→ Response: "Hello! Welcome to Acme Corp. How may I assist you today?"
- User: "Good morning"
→ Response: "Good morning! Welcome to Acme Corp. How may I assist you today?"Step 3:测试
你: "Hi Claude"
Claude: (自动加载 hello-skill)
"Hello! Welcome to Acme Corp. How may I assist you today?"关键学习点
✅ YAML Frontmatter - 正确格式 ✅ description - 包含触发条件"when user says hello" ✅ 清晰指令 - 具体回复模板 ✅ 示例 - 帮助 Claude 理解预期行为
实战 2:Markdown Report Skill(30 分钟进阶)
场景
创建标准化的 Markdown 报告,包含固定格式和样式。
Step 1:创建文件夹结构
mkdir -p ~/.claude/skills/markdown-report
cd ~/.claude/skills/markdown-report
mkdir templates examplesStep 2:创建模板文件
templates/report_template.md
# {Title}
**Date**: {Date}
**Author**: {Author}
---
## Executive Summary
{Summary}
## Key Findings
1. {Finding 1}
2. {Finding 2}
3. {Finding 3}
## Recommendations
- {Recommendation 1}
- {Recommendation 2}
## Conclusion
{Conclusion}
---
*Generated by Acme Reporting System*Step 3:创建 SKILL.md
---
name: markdown-report
description: Generate formatted Markdown reports with standard template. Use for creating reports, summaries, or documentation.
---
# Markdown Report Generator
## Purpose
Create professional Markdown reports following company template.
## Template Structure
Use the template in `templates/report_template.md` with these sections:
- Executive Summary
- Key Findings (3-5 points)
- Recommendations
- Conclusion
## Process
1. Ask user for:
- Report title
- Key findings
- Recommendations
2. Load template from `templates/report_template.md`
3. Replace placeholders:
- `{Title}` - Report title
- `{Date}` - Current date
- `{Author}` - User's name or "Acme Team"
- `{Summary}` - Brief overview
- `{Finding X}` - Key points
- `{Recommendation X}` - Action items
4. Save as `Report_YYYY-MM-DD.md`
## Style Guidelines
- Use **bold** for emphasis
- Use bullet points for lists
- Keep Executive Summary under 200 words
- Each finding should be one clear sentence
## Example Output
See `examples/sample_report.md`Step 4:创建示例文件
examples/sample_report.md
# Q4 Sales Analysis
**Date**: 2024-11-14
**Author**: Acme Team
---
## Executive Summary
Q4 sales exceeded targets by 15%, driven by strong performance in the enterprise segment. Customer retention improved to 94%, while new customer acquisition grew 22% year-over-year.
## Key Findings
1. Enterprise segment contributed 60% of total revenue growth
2. Customer retention rate improved from 89% to 94%
3. Average deal size increased by 18%
## Recommendations
- Increase investment in enterprise sales team
- Launch customer success program to maintain retention
- Develop upsell strategy for existing accounts
## Conclusion
Strong Q4 performance positions us well for next year's growth targets.
---
*Generated by Acme Reporting System*Step 5:测试使用
你: "Create a Q4 sales report"
Claude: (加载 markdown-report Skill)
"I'll help you create a Q4 sales report using our standard template.
Please provide:
1. Key findings (3-5 points)
2. Main recommendations
3. Brief summary"
你: [提供信息]
Claude: (生成报告)
"Report created: Report_2024-11-14.md
Preview:
# Q4 Sales Analysis
[完整内容...]"关键学习点
✅ 模板文件 - 分离模板和逻辑 ✅ 占位符 - 使用 {Variable} 格式 ✅ 示例文件 - 提供参考 ✅ 清晰流程 - 步骤化指导
实战 3:CSV Data Analyzer(60 分钟高级)
场景
分析 CSV 文件并生成可视化报告,包含 Python 脚本执行。
Step 1:创建完整结构
mkdir -p ~/.claude/skills/csv-analyzer
cd ~/.claude/skills/csv-analyzer
mkdir scripts templates output examplesStep 2:创建 Python 分析脚本
scripts/analyze.py
#!/usr/bin/env python3
import pandas as pd
import sys
import json
def analyze_csv(file_path):
"""Analyze CSV and return summary statistics"""
df = pd.read_csv(file_path)
analysis = {
"rows": len(df),
"columns": list(df.columns),
"numeric_summary": df.describe().to_dict(),
"missing_values": df.isnull().sum().to_dict(),
"data_types": df.dtypes.astype(str).to_dict()
}
return analysis
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python analyze.py <csv_file>")
sys.exit(1)
result = analyze_csv(sys.argv[1])
print(json.dumps(result, indent=2))Step 3:创建可视化脚本
scripts/visualize.py
#!/usr/bin/env python3
import pandas as pd
import matplotlib.pyplot as plt
import sys
def create_charts(csv_file, output_dir="output"):
"""Create basic charts from CSV data"""
df = pd.read_csv(csv_file)
# Get numeric columns
numeric_cols = df.select_dtypes(include=['number']).columns
# Create charts for first 3 numeric columns
for i, col in enumerate(numeric_cols[:3]):
plt.figure(figsize=(10, 6))
df[col].plot(kind='hist', bins=20)
plt.title(f'Distribution of {col}')
plt.xlabel(col)
plt.ylabel('Frequency')
plt.savefig(f'{output_dir}/chart_{i+1}_{col}.png')
plt.close()
print(f"Charts saved to {output_dir}/")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python visualize.py <csv_file>")
sys.exit(1)
create_charts(sys.argv[1])Step 4:创建 SKILL.md
---
name: csv-analyzer
description: Analyze CSV files and generate summary statistics with visualizations. Use when user needs data analysis or wants to explore CSV data.
allowed-tools:
- Read
- Bash
- Write
---
# CSV Data Analyzer
## Purpose
Analyze CSV data files and provide insights with charts.
## Capabilities
- Summary statistics (mean, median, std, min, max)
- Data type detection
- Missing value analysis
- Distribution charts
- Correlation analysis
## Requirements
- Python 3.7+
- pandas
- matplotlib
Install dependencies:
```bash
pip install pandas matplotlibUsage Process
1. Load CSV File
Ask user for CSV file path or let them provide the file.
2. Run Analysis
python scripts/analyze.py data.csvThis outputs:
- Row/column counts
- Data types
- Summary statistics
- Missing values
3. Generate Charts
python scripts/visualize.py data.csvCreates distribution charts for numeric columns in output/ folder.
4. Generate Report
Combine analysis results into a markdown report:
- Data overview
- Key statistics
- Charts (embedded as images)
- Insights and recommendations
Output Format
Analysis Report: analysis_report_YYYY-MM-DD.md
Charts: output/chart_1_*.png, output/chart_2_*.png, etc.
Example Workflow
User: "Analyze my sales data"
Claude:
1. Load sales.csv
2. Run: python scripts/analyze.py sales.csv
3. Run: python scripts/visualize.py sales.csv
4. Generate report with findings
5. Return: "Analysis complete! Found 3 insights..."Template Report
See templates/analysis_report_template.md for report format.
Troubleshooting
Error: pandas not found → Run: pip install pandas matplotlib
Error: CSV parsing failed → Check file encoding (use UTF-8) → Verify delimiter (comma vs semicolon)
Examples
See examples/sample_analysis.md for a complete analysis example.
### Step 5:创建报告模板
`templates/analysis_report_template.md`
```markdown
# Data Analysis Report
**File**: {filename}
**Date**: {date}
## Data Overview
- **Rows**: {row_count}
- **Columns**: {column_count}
- **Data Types**: {data_types}
## Summary Statistics
{statistics_table}
## Missing Values
{missing_values_table}
## Key Insights
1. {insight_1}
2. {insight_2}
3. {insight_3}
## Visualizations


## Recommendations
- {recommendation_1}
- {recommendation_2}
---
*Generated by CSV Analyzer Skill*Step 6:创建示例
examples/sample_data.csv
date,sales,region,product
2024-01-01,1500,North,Widget A
2024-01-02,2300,South,Widget B
2024-01-03,1800,East,Widget A
2024-01-04,2100,West,Widget B
2024-01-05,1900,North,Widget Cexamples/sample_analysis.md
# Data Analysis Report
**File**: sample_data.csv
**Date**: 2024-11-14
## Data Overview
- **Rows**: 5
- **Columns**: 4
- **Data Types**: date(object), sales(int64), region(object), product(object)
## Summary Statistics
| Metric | Sales |
|--------|-------|
| Mean | 1920 |
| Median | 1900 |
| Std | 291 |
| Min | 1500 |
| Max | 2300 |
## Missing Values
No missing values detected.
## Key Insights
1. Average sales: $1,920 per transaction
2. Sales range: $1,500 - $2,300 (15% variance)
3. Most common region: North (2 occurrences)
## Visualizations

## Recommendations
- Investigate South region's high performance
- Consider promoting Widget B (highest sales)
- Maintain consistent sales in North region
---
*Generated by CSV Analyzer Skill*Step 7:测试完整流程
你: "Analyze this sales CSV file"
[上传 sales.csv]
Claude: (加载 csv-analyzer Skill)
"I'll analyze your sales data using the CSV Analyzer skill.
Running analysis..."
[执行: python scripts/analyze.py sales.csv]
"Analysis complete! Here's what I found:
- 100 rows, 5 columns
- Average sales: $2,340
- 3 missing values in 'region' column
Generating visualizations..."
[执行: python scripts/visualize.py sales.csv]
"Charts created! Generating report..."
[创建 analysis_report_2024-11-14.md]
"Report ready: analysis_report_2024-11-14.md
Key insights:
1. Sales peaked in Q3
2. North region underperforming
3. Strong correlation between price and sales"关键学习点
✅ 执行代码 - Python 脚本集成 ✅ 多步骤流程 - 分析 → 可视化 → 报告 ✅ 错误处理 - Troubleshooting 部分 ✅ 依赖管理 - 明确 requirements ✅ 完整示例 - 端到端演示
🎓 Skill 开发最佳实践
1. 从简单开始
第一版: 基本功能
↓
第二版: 添加模板
↓
第三版: 添加脚本
↓
第四版: 完善文档2. 测试驱动开发
## Test Cases
### Test 1: Basic Analysis
Input: simple.csv (5 rows, 3 columns)
Expected: Summary statistics + 2 charts
### Test 2: Large File
Input: large.csv (10000 rows)
Expected: Complete within 30 seconds
### Test 3: Missing Data
Input: incomplete.csv (20% missing)
Expected: Report missing value locations3. 版本控制
# 使用 Git 管理 Skill
cd ~/.claude/skills/csv-analyzer
git init
git add .
git commit -m "Initial CSV analyzer skill"4. 文档优先
顺序:
- 写 README(给人看)
- 写 SKILL.md(给 Claude 看)
- 写代码(实现功能)
- 写示例(验证效果)
🐛 常见问题排查
问题 1:Claude 不使用我的 Skill
可能原因:
description 不够具体
markdown# ❌ 太模糊 description: Data tool # ✅ 具体明确 description: Analyze CSV files and generate statistics. Use when working with CSV data.文件路径错误
bash# 检查文件位置 ls ~/.claude/skills/your-skill/SKILL.md # 应该存在YAML 格式错误
yaml# ❌ 错误 name:csv-analyzer # 缺少空格 # ✅ 正确 name: csv-analyzer
问题 2:脚本执行失败
排查步骤:
# 1. 检查脚本权限
chmod +x scripts/analyze.py
# 2. 测试脚本单独运行
python scripts/analyze.py test.csv
# 3. 检查依赖
pip list | grep pandas
# 4. 查看错误日志
claude --debug问题 3:Skill 加载慢
优化方案:
# 分离大文件
large-skill/
├── SKILL.md # 主文件(简洁)
├── detailed_guide.md # 详细文档(按需加载)
└── examples/ # 示例(按需加载)
└── 100_examples.md📋 开发检查清单
创建 Skill 前:
- [ ] 明确单一功能
- [ ] 选择存储位置
- [ ] 设计文件结构
编写 SKILL.md:
- [ ] YAML 格式正确
- [ ] description 包含触发词
- [ ] 步骤清晰具体
- [ ] 示例完整
测试验证:
- [ ] 手动测试脚本
- [ ] Claude 正确触发
- [ ] 输出符合预期
- [ ] 错误处理完善
🎯 进阶挑战
尝试创建这些 Skill:
Git Commit Message Generator
- 分析 git diff
- 生成规范的 commit message
- 遵循 Conventional Commits
Code Review Checklist
- 检查代码质量
- 应用团队 coding standards
- 生成 review 报告
API Documentation Generator
- 读取 OpenAPI spec
- 生成 Markdown 文档
- 包含示例代码
下一步: 2.4 进阶技巧和最佳实践 - 学习高级技巧和团队协作!